<template>
	<a-button type="primary" style="width: 100%" @click="open = true"
		>选择数据集{{ props.paramsJson.name ? `(${props.paramsJson.name})` : '' }}</a-button
	>
	<!-- <div class="json-tree">
		<div v-if="!processedData.length" class="h-[300px] flex items-center justify-center">暂无可选数据</div>
		<template v-else>

			<div v-for="category in processedData" :key="category.id">
				<template v-if="!hasChildren(category) && allowRootSelect">
					<div
						class="category-item"
						:class="{ selected: props.modelValue === `${category.id}` }"
						@click="handleRootSelect(category.id, category)"
					>
						<span>{{ category.name || category.lable }}</span>
					</div>
				</template>

				<template v-else>
					<div
						class="category-header"
						:class="{ expandable: hasChildren(category) }"
						@click="hasChildren(category) && toggleCategory(category.id)"
					>
						<span>{{ category.name || category.lable }}</span>
						<span v-if="hasChildren(category)">
							<CaretRightOutlined :class="[isCategoryExpanded[category.id] ? 'isCategory rotate' : 'isCategory']" />
						</span>
					</div>
					<ul v-if="hasChildren(category) && isCategoryExpanded[category.id]">
						<li
							v-for="(option, optionIndex) in category.children"
							:key="optionIndex"
							:class="{ selected: props.modelValue === `${option.id}` }"
							@click="handleOptionSelect(`${option.id}`, option)"
						>
							{{ option.name || option.lable }}
						</li>
					</ul>
				</template>
			</div>
		</template>
	</div> -->
	<!-- 类别选择 -->
	<a-modal v-model:open="open" title="选择数据集" @ok="handleOk" @cancel="open = false">
		<div class="h-[400px] mt-[20px]">
			<a-row :gutter="[10, 10]">
				<a-col :span="16">
					<a-input v-model:value="searchFormState" style="width: 100%" />
				</a-col>
				<a-col :span="4">
					<a-button style="width: 100%; font-weight: 600" type="primary" @click="querylist">搜索</a-button>
				</a-col>
				<a-col :span="4">
					<a-button style="width: 100%; font-weight: 600" @click="searchFormState = ''">重置</a-button>
				</a-col>
				<a-col :span="24" class="h-[340px] overflow-y-auto">
					<div class="flex items-center justify-center h-[100%] w-[100%]" v-if="options.length === 0">
						<a-spin />
					</div>
					<a-collapse v-model:activeKey="activeKeys" v-else>
						<a-collapse-panel v-for="parent in options" :key="parent.id">
							<template #header>
								<span class="header-text">{{ parent.name }}</span>
							</template>

							<a-radio-group v-model:value="sourceId">
								<a-row :gutter="[10, 10]">
									<a-col :span="24" v-for="child in parent.config.indicators" :key="child.id">
										<a-radio :value="child.id">
											{{ child.name }}
										</a-radio>
									</a-col>
								</a-row>
							</a-radio-group>
						</a-collapse-panel>
					</a-collapse>
				</a-col>
			</a-row>
		</div>
	</a-modal>
</template>

<script setup>
	import { computed, ref, watch, onMounted, reactive } from 'vue'
	import { designStore } from '@/views/plugin/dashboard/store'
	const useDesignStore = designStore()

	const props = defineProps({
		// 选中的 id
		modelValue: {
			type: String,
			default: ''
		},
		// 初始选中的接口
		paramsJson: {
			type: Object,
			default() {
				return {}
			}
		}
	})
	const emit = defineEmits(['update:modelValue', 'update:paramsJson', 'onChange'])

	// 模拟接口返回的数据
	const processedData = computed(() => {
		return [
			{
				lable: '字符串',
				id: '1',
				type: 'string',
				children: [
					{ lable: '广东GDP', title: '广东GDP', id: '1001', numValue: '10000w', pid: '1' },
					{ lable: '70老年人占比', title: '70老年人占比', id: '1002', numValue: '40%', pid: '1' },
					{ lable: '学校总人数', title: '学校总人数', id: '1003', numValue: '17000', pid: '1' }
				]
			},
			{
				lable: '数字',
				id: '2',
				type: 'number',
				children: [
					{ lable: '总得分', title: '总得分', id: '2001', numValue: '300', pid: '2' },
					{ lable: '2025高考总人数', title: '2025高考总人数', id: '2002', numValue: '5600w', pid: '2' },
					{ lable: '教室空闲总数', title: '教室空闲总数', id: '2003', numValue: '4', pid: '2' }
				]
			}
		]
	})

	// 每个分类的展开状态
	const isCategoryExpanded = ref({})
	// 切换分类的展开状态
	const toggleCategory = (categoryId) => {
		isCategoryExpanded.value[categoryId] = !isCategoryExpanded.value[categoryId]
	}

	// 判断数据是否包含子集
	const hasAnyChildren = computed(() => {
		return processedData.value.some((item) => hasChildren(item))
	})

	// 是否允许选择一级节点（当没有任何子集时允许）
	const allowRootSelect = computed(() => !hasAnyChildren.value)

	// 判断单个项目是否有子集
	const hasChildren = (item) => {
		return item.children && item.children.length > 0
	}

	// 选择一级节点
	const handleRootSelect = (categoryId, category) => {
		emit('update:modelValue', categoryId)
		emit('update:paramsJson', selseData.value)
	}

	// 选择二级节点
	const handleOptionSelect = (id, option) => {
		emit('update:modelValue', id)
		emit('update:paramsJson', selseData.value)
	}
	// 默认展开选中值
	watch(
		() => props.modelValue,
		(newVal) => {
			processedData.value.forEach((parent) => {
				parent.children.forEach((child) => {
					if (child.id === newVal) {
						isCategoryExpanded.value[child.pid] = true
					}
				})
			})
		},
		{ immediate: true }
	)

	// ----------------------------- 弹窗 ---------------------------
	const open = ref(false)
	// 当前选中的值
	const sourceId = ref()
	// 查询的内容
	const searchFormState = ref(null)
	// 展开的面板keys
	const activeKeys = ref([])
	// 展开的面板keys
	const options = ref([])
	// 选中的数据
	const selseData = ref({})
	// 反查选中的数据接口参数
	watch(
		() => sourceId.value,
		(newVal) => {
			useDesignStore.dataSource.forEach((parent) => {
				parent.config.indicators.forEach((child) => {
					if (child.id === newVal) {
						selseData.value = child
						activeKeys.value = [parent.id]
					}
				})
			})
		}
	)
	// 反查选中的数据接口参数
	watch(
		() => props.paramsJson,
		(newVal) => {
			useDesignStore.dataSource.forEach((parent) => {
				parent.config.indicators.forEach((child) => {
					if (child.id === newVal.id) {
						sourceId.value = child.id
					}
				})
			})
		},
		{
			immediate: true,
			deep: true
		}
	)
	const handleOk = (e) => {
		open.value = false
		emit('update:paramsJson', selseData.value)
		console.log(selseData.value)
		console.log(props.paramsJson)
		console.log(selseData.value !== props.paramsJson)
		if (selseData.value.id !== props.paramsJson.id) {
			emit('onChange', selseData.value)
		}
		// 去掉接口
	}
	const querylist = async () => {
		options.value = []
		options.value = await useDesignStore.getDataSource({ searchFormState: searchFormState.value })
	}
	onMounted(() => {
		querylist()
	})
</script>

<style scoped>
	.json-tree {
		--tree-indent: 10px;
		--primary-color: #2196f3;
		--text-color: #333;
		font-family: 'Menlo', 'Consolas', monospace;
		padding: 8px;
		border: 1px solid #eee;
		border-radius: 2px;
		background: white;
		transition: all 0.3s;
	}

	.category-header {
		cursor: pointer;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 8px;
		background-color: #f5f6f7;
		transition: all 0.3s;
		border-radius: 2px;
	}

	.category-header:hover {
		background-color: #f0f0f0;
		transition: all 0.3s;
	}
	.isCategory {
		transition: all 0.3s;
	}
	.rotate {
		transform: rotate(90deg);
	}

	.category-item {
		cursor: pointer;
		padding: 8px;
		margin: 4px 0;
		border-radius: 2px;
		transition: background-color 0.2s;
		transition: all 0.3s;
	}

	.category-item:hover {
		background-color: #eeeeee;
		transition: all 0.3s;
	}

	.category-item.selected {
		background-color: var(--primary-color);
		color: white;
		transition: all 0.3s;
	}

	.category-header.expandable {
		cursor: pointer;
	}

	.category-header:not(.expandable) {
		cursor: default;
		opacity: 0.7;
	}

	ul {
		list-style-type: none;
		transition: all 0.3s;
		padding: 10px 15px;
		margin-bottom: 0px;
	}

	li {
		cursor: pointer;
		padding-left: 20px;
		height: 30px;
		display: flex;
		align-items: center;
		border-radius: 2px;
		transition: all 0.3s;
	}

	li.selected {
		background-color: #1677ff;
		color: white;
	}
</style>
